<?php



namespace app\api\service;
use app\api\service\Order as OrderService;
use think\Exception;
use think\facade\Log;

include_once ($_SERVER['DOCUMENT_ROOT'] . "/../extend/WxPay/WxPay.Api.php");

class Pay
{
    protected static $orderId;
    protected static $orderNo;

    public static function pay($orderId)
    {
        // 检查订单信息是否有效
        $orderInfo = OrderService::orderIsValid($orderId);

        // 检查库存量是否充足
        $status = OrderService::getOrderStatusByOrderId($orderId);

        if (!$status['pass'])
        {
            T(601006);
        }

        // 提交微信的预订单
        return self::makeWxPreOrder($status, $orderInfo);
    }

    private static function makeWxPreOrder($status, $orderInfo)
    {
        $openId =Token::getTokenVal('openid');
        $wxOrderData =new \WxPayUnifiedOrder();
        $wxOrderData->SetOpenid($openId);
        $wxOrderData->SetOut_trade_no($orderInfo['order_no']);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($status['orderPrice'] * 100);
        $wxOrderData->SetBody('Pily美食汇');
        $wxOrderData->SetNotify_url('qq.com');  // 回调地址

        $config = new \WxPayConfig();
        // 提交微信的预订单
        // https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
        $wxOrder = \WxPayApi::unifiedOrder($config, $wxOrderData);

        if ($wxOrder['return_code'] != 'SUCCESS' ||
            $wxOrder['result_code' != 'SUCCESS']
        )
        {
            Log::record($wxOrder, 'error');
            Log::record('获取预支付订单失败', 'error');
            throw new Exception($wxOrder['return_msg']);
        }

        // 保存微信返回的预订单ID  prepay_id
        OrderService::savePrepayId($orderInfo['id'], $wxOrder['prepay_id']);

        // 返回小程序拉起支付所需的签名paySign，为了防止参数被篡改
        // https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
        $signature = self::makeSignature($wxOrder, $config);
        return $signature;
    }

    /**
     * 组装签名参数返回给客户端
     * @param $wxOrder
     * @param $config
     * @return array
     * @throws \WxPayException
     */
    private static function makeSignature($wxOrder, $config)
    {
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0,9999));
        $jsApiPayData->SetNonceStr($rand);
        $jsApiPayData->SetSignType('MD5');
        $jsApiPayData->SetPackage('prepay_id='.$wxOrder['prepay_id']);
        $sign = $jsApiPayData->MakeSign($config);
        $rawValues = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;
        return $rawValues;
    }
}